<template>
  <view
      class="drag-icon"
      :style="{ transform: `translate(${dragX}px, ${dragY}px)` }"
      @touchstart="handleDragStart"
      @touchmove.prevent="handleDragMove"
      @touchend="handleDragEnd"
      @mousedown="handleDragStart"
      @mousemove.prevent="handleDragMove"
      @mouseup="handleDragEnd"
  >
    <image
        src="@/static/shuju.png"
        class="icon-image"
    />
  </view>
</template>
<script>
export default {
  name: "dragIcon",
  props: {
    windowWidth: Number,
    windowHeight: Number,
  },
  data() {
    return {
      // 新增拖拽相关数据
      dragX: 0,
      dragY: 0,
      isDragging: false,
      startX: 0,
      startY: 0,
      initialX: 0,
      initialY: 0,
      startTime: null,
      isclick: false
    }
  },
  mounted() {
    // 初始化居中位置
  },
  watch: {
    windowWidth: {
      handler(newVal) {
        this.dragX = (this.windowWidth - 100) / 2 - 30// 50为图标宽度
      },
      deep: true,
      immediate: true,
    },
    windowHeight: {
      handler(newVal) {
        this.dragY = (this.windowHeight)  // 50为图标宽度
      },
      deep: true,
      immediate: true,
    }
  },
  methods: {
    // 新增拖拽方法
    handleDragStart(e) {
      this.startTime = Date.now()
      if (!this.isclick) {
        const touch = e.touches ? e.touches[0] : e
        this.isDragging = true
        if (touch) {
          this.startX = touch.clientX
          this.startY = touch.clientY
        }
        this.initialX = this.dragX
        this.initialY = this.dragY
      }
    },
    handleDragMove(e) {
      if (!this.isDragging) return
      const touch = e.touches ? e.touches[0] : e
      let deltaX = 0
      let deltaY = 0
      if (touch) {
        deltaX = touch.clientX - this.startX
        deltaY = touch.clientY - this.startY
      }
      // 边界限制（保持图标在屏幕内）
      const maxX = this.windowWidth
      const maxY = this.windowHeight

      this.dragX = Math.max(0, Math.min(maxX, this.initialX + deltaX))
      this.dragY = Math.max(0, Math.min(maxY, this.initialY + deltaY))
    },
    handleDragEnd() {
      if (Date.now() - this.startTime < 300) {
        this.isclick = true
        this.handleIconClick() // 触发点击事件
        return
      }
      this.isDragging = false

      // 右侧吸附逻辑
      if (this.dragX > this.windowWidth * 0.7) {
        this.dragX = this.windowWidth - 60
      }
      // 左侧吸附逻辑
      else if (this.dragX < this.windowWidth * 0.3) {
        this.dragX = 10
      }
    },
    handleIconClick() {
      this.$emit('click');
      this.isclick = false
    }
  }
}
</script>
<style scoped lang="scss">
.drag-icon {
  position: fixed;
  width: 100rpx;
  height: 100rpx;
  z-index: 9999;
  transition: transform 0.1s ease-out; /* 添加平滑过渡 */
  touch-action: none; /* 禁用默认触摸行为 */
  background-color: rgba(255, 255, 255, 0.1);

  /* 拖拽反馈效果 */
  &.dragging {
    opacity: 0.8;
    transform: scale(1.1);
  }

  .icon-image {
    width: 100%;
    height: 100%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>